package com.dysm.spring.security.auth;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.oauth2.common.exceptions.UserDeniedAuthorizationException;


/**
 * 密码模式授权token
 */
public class PasswordGrantTokenAuthenticationManager implements AuthenticationManager {

    private final Logger LOG = LoggerFactory.getLogger(this.getClass());

    private final UserDetailsService userDetailsService;

    private final BCryptPasswordEncoder bCryptPasswordEncoder;

    public PasswordGrantTokenAuthenticationManager(UserDetailsService userDetailsService, BCryptPasswordEncoder bCryptPasswordEncoder) {
        this.userDetailsService = userDetailsService;
        this.bCryptPasswordEncoder = bCryptPasswordEncoder;
    }

    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        if (authentication == null) {
            throw new UserDeniedAuthorizationException("Invalid User (user not found)");
        }
        String username = (String) authentication.getPrincipal();
        String password = (String) authentication.getCredentials();
        UserDetails userDetails = userDetailsService.loadUserByUsername(username);
        if (userDetails == null) {
            throw new UserDeniedAuthorizationException("Invalid username: " + username);
        }
        String loadPassword = userDetails.getPassword();
        LOG.info("bCryptPasswordEncoder：" + bCryptPasswordEncoder);
        String encodePassword = bCryptPasswordEncoder.encode(password);
        LOG.info(loadPassword + "loadPassword");
        LOG.info(encodePassword + "encodePassword");
        if (!bCryptPasswordEncoder.matches(password, loadPassword)) {
            throw new UserDeniedAuthorizationException("Invalid username or password");
        }
        return new UsernamePasswordAuthenticationToken(username, password, userDetails.getAuthorities());
    }
}
